<template>
  <v-card style="width:100%;height:90vh">
    <v-container fluid class="pa-0">
      <!-- 添加导出按钮 -->
      <v-row dense style="padding:0 20px 0 0;position:absolute;right:0;top:10px;z-index:1">
        <v-col cols="auto" class="d-flex align-center">
          <v-tooltip bottom>
            <template v-slot:activator="{ on, attrs }">
              <v-btn
                icon
                color="success"
                @click="exportExcel"
                class="mr-2"
                v-bind="attrs"
                v-on="on"
                style="width: 36px; height: 36px"
              >
                <v-icon size="24">mdi-file-excel</v-icon>
              </v-btn>
            </template>
            <span>导出Excel</span>
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on, attrs }">
              <v-btn
                icon
                color="primary"
                @click="exportChart"
                v-bind="attrs"
                v-on="on"
                style="width: 36px; height: 36px"
              >
                <v-icon size="24">mdi-image</v-icon>
              </v-btn>
            </template>
            <span>导出图片</span>
          </v-tooltip>
        </v-col>
      </v-row>

      <!-- 顶部搜索栏（缺陷分布分析） -->
      <v-row dense style="padding:10px 20px;margin-bottom:-25px">
        <v-col cols="1">
          <v-select  dense :items="types" @change="loadDefectData()" label="类型" v-model="defect_lamp_type"></v-select>
        </v-col>
        <v-col cols="1">
          <v-select  dense :items="bases" @change="loadDefectData()" label="基地" v-model="defect_base"></v-select>
        </v-col>
        
        <v-col cols="2">
          <VZDatePicker  dense v-model="defect_month" label="灯具制造月份范围" type="monthrange" @input="loadDefectData()"></VZDatePicker>
        </v-col>
        <v-col  cols="2">
            <v-combobox dense v-model="defectMainPlant" :items="mainPlantItems" @change="loadDefectData()" label="主机厂" clearable ></v-combobox>
      </v-col>
        <v-col cols="2">
          <v-select  dense :items="misOptions" @change="loadDefectData()" label="MIS" v-model="defect_mis"></v-select>
        </v-col>
        <v-col cols="2">
          <v-select dense :items="defectTypeItems" @change="loadDefectData()" label="缺陷统计类型" v-model="defectType"></v-select>
        </v-col>
        <!--          <v-col cols="2">
                    <v-form @submit.prevent="loadDefectData" >
                      <v-text-field  label="简称搜索" dense v-model="defect_simple_call" clearable append-icon="mdi-magnify" @click:append="loadDefectData"></v-text-field>
                    </v-form>
                  </v-col>-->
        <v-col cols="1">
          <v-tooltip bottom style="position:relative;top:2px;right:2px">
            <template v-slot:activator="{ on, attrs }">
              <v-icon
                  color="primary"
                  dark
                  v-bind="attrs"
                  v-on="on"
              >
                mdi-help-rhombus
              </v-icon>
            </template>
            <h4>当前图表说明：</h4>
            <p>1、当前图表统计的所有月份或者日期都是MQP售后数据的【灯具制造日期】。</p>
            <p>2、点击左侧缺陷统计类型可使下方图表按照不同的维度统计缺陷分布。</p>
          </v-tooltip>
        </v-col>
      </v-row>

      <!-- 上半部分：缺陷分布总和 -->
      <v-row no-gutters >
        <!-- 左侧柱状图 -->
        <v-col cols="7">
          <v-card class="mx-1">
            <v-card-title class="subtitle-1 py-0" style="font-size:14px">缺陷分布总和</v-card-title>
            <div ref="defectBarTarget" style="width:100%;height:35vh"></div>
          </v-card>
        </v-col>
        <!-- 右侧饼图 -->
        <v-col cols="5">
          <v-card class="mx-1" >
            <v-card-title class="subtitle-1 py-0" style="font-size:14px">产品简称分布</v-card-title>
            <div ref="defectPieTarget" style="width:100%;height:35vh"></div>
          </v-card>
        </v-col>
      </v-row>

      <div style="height:10px;flex-shrink:0"></div>

      <!-- 中间搜索栏（退回产品分析） -->
      <v-row dense style="padding:2px 20px;margin-bottom:-18px">
        <v-col cols="1">
          <v-select  dense :items="types" @change="loadReturnData()" label="类型" v-model="return_lamp_type"></v-select>
        </v-col>
        <v-col cols="1">
          <v-select  dense :items="bases" @change="loadReturnData()" label="基地" v-model="return_base"></v-select>
        </v-col>
                
        <v-col cols="2">
          <VZDatePicker dense v-model="return_month" label="灯具制造月份范围" type="monthrange" @input="loadReturnData()"></VZDatePicker>
        </v-col>
        <v-col  cols="2">
            <v-combobox dense v-model="returnMainPlant" :items="mainPlantItems" @change="loadReturnData()" label="主机厂" clearable ></v-combobox>
      </v-col>
        <v-col cols="2">
          <v-form @submit.prevent="loadReturnData" >
            <v-text-field label="简称搜索" dense v-model="return_simple_call" clearable append-icon="mdi-magnify" @click:append="loadReturnData"></v-text-field>
          </v-form>
        </v-col>
        <v-col cols="2">
          <v-select dense :items="defectTypeItems" @change="loadLineRateData()" label="缺陷统计类型" v-model="returnDefectType"></v-select>
        </v-col>
        <v-col cols="1">
          <v-tooltip bottom style="position:relative;top:2px;right:2px">
            <template v-slot:activator="{ on, attrs }">
              <v-icon
                  color="primary"
                  dark
                  v-bind="attrs"
                  v-on="on"
              >
                mdi-help-rhombus
              </v-icon>
            </template>
            <h4>当前图表说明：</h4>
            <p>1、当前图表统计的所有月份或者日期都是MQP售后数据的【灯具制造日期】。</p>
            <p>2、点击左侧缺陷统计类型可使右下方图表按照不同的维度统计缺陷分布。</p>
          </v-tooltip>
        </v-col>
      </v-row>

      <!-- 下半部分：退回产品排布 -->
      <v-row no-gutters >
        <!-- 左侧柱状图 -->
        <v-col cols="7">
          <v-card class="mx-1" >
            <v-card-title class="subtitle-1 py-0" style="font-size:14px">退回产品排布<span v-if="returnNameList && returnNameList.length" class="ml-auto" style="color:#FF5722;font-weight:bold">总计: {{ calculateTotalCount() }}</span></v-card-title>
            <div ref="returnBarTarget" style="width:100%;height:35vh"></div>
          </v-card>
        </v-col>
        <!-- 右侧折线图 -->
        <v-col cols="5">
          <v-card class="mx-1" >
            <v-card-title class="subtitle-1 py-0" style="font-size:14px">缺陷统计</v-card-title>
            <div ref="returnLineTarget" style="width:100%;height:35vh"></div>
          </v-card>
        </v-col>
      </v-row>

    </v-container>
  </v-card>
</template>
<script>
export default {
  data () {
    return {
      // 页面控制
      is_fullscreen: false,
      defect_month:[this.getYearFirstMonth(),this.getCurrentMonth()],
      defect_mis: '3MIS',
      defect_lamp_type: 'FRONT_LAMP',
      defect_base: '',
      defect_simple_call: '',
      defectType:'DESCRIBE',
      defectMainPlant:'',

      // 退回产品分析筛选参数
      return_month: [this.getYearFirstMonth(),this.getCurrentMonth()],
      return_mis: '3MIS',
      return_lamp_type: 'FRONT_LAMP',
      return_base: '',
      return_simple_call: '',
      returnDefectType:'DESCRIBE',
      returnMainPlant:'',

      // 共用参数
      defectTypeItems:[{text:'用户简述',value:'DESCRIBE'},{text:'初步分析结果',value:'DEFECT'}],
      types: [],
      bases: [],
      mainPlantItems:[],
      misOptions: [
        { text: '3MIS', value: '3MIS' },
        { text: '6MIS', value: '6MIS' },
        { text: '9MIS', value: '9MIS' },
        { text: '12MIS', value: '12MIS' },
        { text: '24MIS', value: '24MIS' },
        { text: '36MIS', value: '36MIS' }
      ],

      // 缺陷分布总和页面
      defect_bar_sql: "SELECT ifnull(d.FIRST_ANALYSE, '无') AS name, count(a.id) AS num FROM tt_sale_record_qms a LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT p ON a.material_id = p.id LEFT JOIN TT_MQP_DEFECT d ON a.defect_id = d.id LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT_REFERRED r ON p.REFERRED_ID = r.id WHERE a.MARK_FOR_DELETE = 0 AND a.material_id IS NOT NULL AND a.MADE_TIME IS NOT NULL AND a.REPAIR_TIME IS NOT NULL AND p.MARK_FOR_DELETE = 0 [AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') >= #{start_month} AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') <= #{end_month}] AND DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN #{misStart} AND #{misEnd} [AND r.lamp_type = #{lamp_type}] [AND a.BASE = #{base}]  [AND a.customer_id = #{customer_id}]  [AND r.SIMPLE_CALL like CONCAT('%',#{simple_call},'%')] GROUP BY d.FIRST_ANALYSE",
      defect_pie_sql: "SELECT ifnull(R.SIMPLE_CALL, '无') AS SIMPLE_CALL, count(a.id) AS num FROM tt_sale_record_qms a LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT p ON a.material_id = p.id LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT_REFERRED r ON p.REFERRED_ID = r.id LEFT JOIN TT_MQP_DEFECT d ON a.defect_id = d.id WHERE a.MARK_FOR_DELETE = 0 AND a.material_id IS NOT NULL AND a.MADE_TIME IS NOT NULL AND a.REPAIR_TIME IS NOT NULL AND p.MARK_FOR_DELETE = 0 AND d.FIRST_ANALYSE = #{defect_name} [AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') >= #{start_month} AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') <= #{end_month}] AND DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN #{misStart} AND #{misEnd} [AND r.lamp_type = #{lamp_type}] [AND a.BASE = #{base}]  [AND a.customer_id = #{customer_id}]  AND r.SIMPLE_CALL IS NOT NULL GROUP BY r.SIMPLE_CALL",
      defect_describe_bar_sql:"SELECT ifnull(a.consumer_describe_extract, '无') AS name, count(a.id) AS num FROM tt_sale_record_qms a LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT p ON a.material_id = p.id LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT_REFERRED r ON p.REFERRED_ID = r.id WHERE a.MARK_FOR_DELETE = 0 AND a.material_id IS NOT NULL AND a.MADE_TIME IS NOT NULL AND a.REPAIR_TIME IS NOT NULL AND p.MARK_FOR_DELETE = 0  [AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') >= #{start_month} AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') <= #{end_month}] AND DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN #{misStart} AND #{misEnd} [AND r.lamp_type = #{lamp_type}] [AND a.BASE = #{base}]  [AND a.customer_id = #{customer_id}]  [AND r.SIMPLE_CALL like CONCAT('%',#{simple_call},'%')] GROUP BY a.consumer_describe_extract",
      defect_describe_pie_sql:"SELECT ifnull(R.SIMPLE_CALL, '无') AS SIMPLE_CALL, count(a.id) AS num FROM tt_sale_record_qms a LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT p ON a.material_id = p.id LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT_REFERRED r ON p.REFERRED_ID = r.id WHERE a.MARK_FOR_DELETE = 0 AND a.material_id IS NOT NULL AND a.MADE_TIME IS NOT NULL AND a.REPAIR_TIME IS NOT NULL AND p.MARK_FOR_DELETE = 0 AND a.consumer_describe_extract = #{defect_name} [AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') >= #{start_month} AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') <= #{end_month}] AND DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN #{misStart} AND #{misEnd} [AND r.lamp_type = #{lamp_type}] [AND a.BASE = #{base}]  [AND a.customer_id = #{customer_id}]  AND r.SIMPLE_CALL IS NOT NULL GROUP BY r.SIMPLE_CALL",
      chartDefectBarTarget: null,
      chartDefectPieTarget: null,
      defectBarData: [],
      defectPieData: [],
      currentDefect: '',
      defectTotalCount: 0,

      // 退回产品排布页面
      return_bar_sql: "select * from (SELECT a.SIMPLE_CALL,a.SIMPLE_CALL_ID,COUNT(CASE WHEN DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN 0 AND 93 THEN 1 END) AS mis3,COUNT(CASE WHEN DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN 94 AND 186 THEN 1 END) AS mis6,COUNT(CASE WHEN DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN 187 AND 279 THEN 1 END) AS mis9,COUNT(CASE WHEN DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN 280 AND 365 THEN 1 END) AS mis12,COUNT(CASE WHEN DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN 366 AND 730 THEN 1 END) AS mis24,COUNT(CASE WHEN DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN 731 AND 1095 THEN 1 END) AS mis36,COUNT(*) AS total_count FROM (SELECT a.id,a.MADE_TIME,a.REPAIR_TIME,a.material_id,p.REFERRED_ID,r.id SIMPLE_CALL_ID,r.SIMPLE_CALL,r.LAMP_TYPE FROM tt_sale_record_qms a LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT p ON a.material_id = p.id LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT_REFERRED r ON p.REFERRED_ID = r.id WHERE a.MARK_FOR_DELETE = 0 AND a.material_id IS NOT NULL AND a.MADE_TIME IS NOT NULL AND a.REPAIR_TIME IS NOT NULL AND p.MARK_FOR_DELETE = 0 AND p.REFERRED_ID IS NOT NULL AND r.MARK_FOR_DELETE = 0 [AND r.lamp_type = #{lamp_type}] [AND a.BASE = #{base}] [AND a.customer_id = #{customer_id}]  [AND r.SIMPLE_CALL like CONCAT('%',#{simple_call},'%')] [AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') >= #{start_month} AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') <= #{end_month}] AND DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN 0 AND 1095) a GROUP BY a.SIMPLE_CALL,a.SIMPLE_CALL_ID) a  ORDER BY a.total_count desc",
      return_line_sql: "SELECT ifnull(d.FIRST_ANALYSE,'无') as name,count(a.id) as num FROM tt_sale_record_qms a LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT p ON a.material_id = p.id left join TT_MQP_DEFECT d on a.defect_id = d.id WHERE a.MARK_FOR_DELETE = 0 AND a.material_id IS NOT NULL AND a.MADE_TIME IS NOT NULL AND a.REPAIR_TIME IS NOT NULL AND p.MARK_FOR_DELETE = 0 [AND p.referred_simple_call = #{referred_simple_call}] [AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') >= #{start_month} AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') <= #{end_month}] [AND a.BASE = #{base}]  [AND a.customer_id = #{customer_id}]  AND DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN #{misStart} AND #{misEnd} group by d.FIRST_ANALYSE",
      return_line_describe_sql: "SELECT ifnull(a.consumer_describe_extract,'无') as name,count(a.id) as num FROM tt_sale_record_qms a LEFT JOIN TB_STANDARD_ASSEMBLY_PRODUCT p ON a.material_id = p.id WHERE a.MARK_FOR_DELETE = 0 AND a.material_id IS NOT NULL AND a.MADE_TIME IS NOT NULL AND a.REPAIR_TIME IS NOT NULL AND p.MARK_FOR_DELETE = 0 [AND p.referred_simple_call = #{referred_simple_call}] [AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') >= #{start_month} AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') <= #{end_month}] [AND a.BASE = #{base}]  [AND a.customer_id = #{customer_id}]  AND DATEDIFF(a.REPAIR_TIME, a.MADE_TIME) BETWEEN #{misStart} AND #{misEnd} group by a.consumer_describe_extract",
      denominator_sql: "SELECT ifnull(SUM(SHIPPED_QTY),0) num FROM tb_part_sendout a LEFT JOIN tb_standard_assembly_product b ON a.matnr = b.ASSEMBLY_CODE WHERE a.YEAR_MONTHS >= #{startDate} and a.YEAR_MONTHS <= #{endDate} and b.referred_simple_call = #{referred_simple_call}",
      chartReturnBarTarget: null,
      chartReturnLineTarget: null,
      returnNameList: [],
      returnSeriesList: [],
      dataZoomStart: 80,
      defectList: [],
      referred_simple_call: '',
    }
  },
  computed: {
    defect_lamp_type_show: function () {
      return app.utils.getEntryValue("LAMP_TYPE", this.defect_lamp_type);
    },
    defect_base_show: function () {
      return app.utils.getEntryValue("MQP_BASE", this.defect_base);
    },
    return_lamp_type_show: function () {
      return app.utils.getEntryValue("LAMP_TYPE", this.return_lamp_type);
    },
    return_base_show: function () {
      return app.utils.getEntryValue("MQP_BASE", this.return_base);
    },
    defectMisRange: function() {
      return this.getDefectMisRange(this.defect_mis);
    },
    returnMisRange: function() {
      return this.getReturnMisRange(this.return_mis);
    },
    return_defect_sql:function() {
      return this.returnDefectType == 'DESCRIBE' ? this.return_line_describe_sql : this.return_line_sql;
    },
    cal_defect_bar_sql:function() {
      return this.defectType == 'DESCRIBE' ? this.defect_describe_bar_sql : this.defect_bar_sql;
    },
    cal_defect_pie_sql:function() {
      return this.defectType == 'DESCRIBE' ? this.defect_describe_pie_sql : this.defect_pie_sql;
    },
    defectMainPlantId:function () {
      return this.defectMainPlant ? this.defectMainPlant.value : '';
    },
    defectMainPlantName:function () {
      return this.defectMainPlant ? this.defectMainPlant.text : '';
    },
    returnMainPlantId:function () {
      return this.returnMainPlant ? this.returnMainPlant.value : '';
    },
    returnMainPlantName:function () {
      return this.returnMainPlant ? this.returnMainPlant.text : '';
    },
  },
  watch: {
    return_month(newValue, oldValue) {
      if (newValue != undefined && newValue != '') {
        this.loadReturnData();
      }
    },
    defect_month(newValue, oldValue) {
      if (newValue != undefined && newValue != '') {
        this.loadDefectData();
      }
    },
  },
  methods: {
    // 计算总数的方法
    calculateTotalCount() {
      let totalCount = 0;
      if (this.returnSeriesList && this.returnSeriesList.length > 0) {
        this.returnSeriesList.forEach(series => {
          series.data.forEach(value => {
            totalCount += parseInt(value || 0);
          });
        });
      }
      return totalCount;
    },

    // 获取当年第一个月
    getYearFirstMonth() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      return `${year}-01`;
    },

    // 导出Excel方法
    exportExcel() {
      try {
        // 准备缺陷分布数据
        let defectData = [];
        if (this.defectBarData && this.defectBarData.length > 0) {
          defectData = this.defectBarData.map(item => {
            return {
              name: item.name,
              count: item.num,
              percent: (item.num / this.defectTotalCount * 100).toFixed(2) + '%'
            };
          });
        }

        // 准备饼图数据
        let pieData = [];
        if (this.defectPieData && this.defectPieData.length > 0) {
          pieData = this.defectPieData.map(item => {
            return {
              simplecall: item.simple_call,
              count: item.num
            };
          });
        }

        // 准备退回产品数据
        let returnData = [];
        if (this.returnNameList && this.returnNameList.length > 0) {
          this.returnNameList.forEach((item, index) => {
            const rowData = {
              name: item.value,
              mis3: this.returnSeriesList[0].data[index] || 0,
              mis6: this.returnSeriesList[1].data[index] || 0,
              mis9: this.returnSeriesList[2].data[index] || 0,
              mis12: this.returnSeriesList[3].data[index] || 0,
              mis24: this.returnSeriesList[4].data[index] || 0,
              mis36: this.returnSeriesList[5].data[index] || 0
            };
            returnData.push(rowData);
          });
        }

        // 准备折线图数据
        let lineData = [];
        if (this.defectList && this.defectList.length > 0) {
          lineData = this.defectList.map(item => {
            return {
              name: item.name,
              count: item.num
            };
          });
        }

        // 创建缺陷分布CSV内容
        let csvContent = '缺陷分布总和\n缺陷名称,数量,百分比\n';
        defectData.forEach(item => {
          csvContent += `${item.name},${item.count},${item.percent}\n`;
        });
        
        // 添加产品简称饼图数据
        if (pieData.length > 0 && this.currentDefect) {
          csvContent += `\n产品简称分布 - ${this.currentDefect}\n产品简称,数量\n`;
          pieData.forEach(item => {
            csvContent += `${item.simplecall},${item.count}\n`;
          });
        }
        
        // 添加退回产品数据
        csvContent += '\n退回产品排布\n产品简称,3MIS,6MIS,9MIS,12MIS,24MIS,36MIS\n';
        returnData.forEach(item => {
          csvContent += `${item.name},${item.mis3},${item.mis6},${item.mis9},${item.mis12},${item.mis24},${item.mis36}\n`;
        });

        // 添加缺陷统计折线图数据
        if (lineData.length > 0 && this.referred_simple_call && this.return_mis) {
          csvContent += `\n缺陷统计 - ${this.referred_simple_call} - ${this.return_mis}\n缺陷名称,数量\n`;
          lineData.forEach(item => {
            csvContent += `${item.name},${item.count}\n`;
          });
        }

        // 使用TextEncoder处理UTF-8编码
        const encoder = new TextEncoder();
        const data = encoder.encode('\ufeff' + csvContent);
        const blob = new Blob([data], { type: 'text/csv;charset=utf-8' });
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = '产品售后数据情况.csv';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
        
        app.$message.success('导出Excel成功');
      } catch (error) {
        console.error('导出Excel失败:', error);
        app.$message.error('导出Excel失败');
      }
    },

    // 导出图表图片
    exportChart() {
      try {
        // 导出缺陷分布柱状图
        if (this.chartDefectBarTarget) {
          let defectBarBase64 = this.chartDefectBarTarget.getDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#ffffff'
          });
          let defectBarLink = document.createElement('a');
          defectBarLink.download = '缺陷分布总和.png';
          defectBarLink.href = defectBarBase64;
          defectBarLink.click();
        }

        // 导出产品简称饼图
        if (this.chartDefectPieTarget) {
          let defectPieBase64 = this.chartDefectPieTarget.getDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#ffffff'
          });
          let defectPieLink = document.createElement('a');
          defectPieLink.download = '产品简称分布.png';
          defectPieLink.href = defectPieBase64;
          defectPieLink.click();
        }

        // 导出退回产品柱状图
        if (this.chartReturnBarTarget) {
          let returnBarBase64 = this.chartReturnBarTarget.getDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#ffffff'
          });
          let returnBarLink = document.createElement('a');
          returnBarLink.download = '退回产品排布.png';
          returnBarLink.href = returnBarBase64;
          returnBarLink.click();
        }

        // 导出缺陷统计折线图
        if (this.chartReturnLineTarget) {
          let returnLineBase64 = this.chartReturnLineTarget.getDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#ffffff'
          });
          let returnLineLink = document.createElement('a');
          returnLineLink.download = '缺陷统计.png';
          returnLineLink.href = returnLineBase64;
          returnLineLink.click();
        }
        
        app.$message.success('导出图表成功');
      } catch (error) {
        console.error('导出图表失败:', error);
        app.$message.error('导出图表失败');
      }
    },

    // 通用方法
    getCurrentMonth() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份补零
      return `${year}-${month}`;
    },
    getFirstDayOfMonth() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      return `${year}-${month}-01`;
    },
    getLastDayOfMonth() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1;
      // 获取当月最后一天（下个月的第0天）
      const lastDay = new Date(year, month, 0).getDate();
      return `${year}-${String(month).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`;
    },
    getDefectMisRange(mis) {
      if(mis == '3MIS'){
        return [0, 93];
      } else if(mis == '6MIS'){
        return [0, 186];
      } else if(mis == '9MIS'){
        return [0, 279];
      } else if(mis == '12MIS'){
        return [0, 365];
      } else if(mis == '24MIS'){
        return [0, 730];
      } else if(mis == '36MIS'){
        return [0, 1095];
      } else {
        return [0, 93]; // 默认3MIS
      }
    },
    getReturnMisRange(mis) {
      if(mis == '3MIS'){
        return [0, 93];
      } else if(mis == '6MIS'){
        return [94, 186];
      } else if(mis == '9MIS'){
        return [187, 279];
      } else if(mis == '12MIS'){
        return [280, 365];
      } else if(mis == '24MIS'){
        return [366, 730];
      } else if(mis == '36MIS'){
        return [731, 1095];
      } else {
        return [0, 93]; // 默认3MIS
      }
    },
    loadTypes(){
      let data = [];
      app.utils.getEntrys('LAMP_TYPE').forEach(item => {
        data.push({
          text: item.name,
          value: item.code
        });
      })
      this.types = data;
    },
    loadBases(){
      let data = [{text: '全部', value: ''}];
      app.utils.getEntrys('MQP_BASE').forEach(item => {
        data.push({
          text: item.name,
          value: item.code
        });
      })
      this.bases = data;
    },
    loadDefectData() {
      // 加载缺陷分析数据
      this.loadDefectBarData();
    },

    loadReturnData() {
      // 加载退回产品数据
      this.loadReturnBarData();
    },

    // 获取日期工具方法
    getMonthStartAndEnd(dateStr) {
      // 验证输入格式
      if (!/^\d{4}-\d{2}$/.test(dateStr)) {
        throw new Error('请输入正确的年月格式，例如："2025-01"');
      }

      // 解析年月
      const [year, month] = dateStr.split('-').map(Number);

      // 创建当月第一天
      const firstDay = new Date(year, month - 1, 1);

      // 创建下个月的第一天，然后减去一天得到当月的最后一天
      const lastDay = new Date(year, month, 0);

      // 格式化日期为 YYYY-MM-DD
      const format = (date) => {
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        return `${y}-${m}-${d}`;
      };

      return [format(firstDay), format(lastDay)];
    },

    // 缺陷分布总和相关方法
    loadDefectBarData() {
      let _this = this;
      let params = {"SQL": this.cal_defect_bar_sql};
      
      // 修改SQL，处理'无'的情况
      if (this.defectType === 'DESCRIBE') {
        params.SQL = this.cal_defect_bar_sql.replace("ifnull(a.consumer_describe_extract, '无') AS name", 
          "CASE WHEN a.consumer_describe_extract IS NULL OR a.consumer_describe_extract = '' THEN '无' ELSE a.consumer_describe_extract END AS name");
      } else {
        params.SQL = this.cal_defect_bar_sql.replace("ifnull(d.FIRST_ANALYSE, '无') AS name", 
          "CASE WHEN d.FIRST_ANALYSE IS NULL OR d.FIRST_ANALYSE = '' THEN '无' ELSE d.FIRST_ANALYSE END AS name");
      }

      app.utils.ajaxRequest({
        hideMsg: true,
        hideMask: true,
        url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
        params: {
          "queryCondition[start_month]": _this.defect_month[0],
          "queryCondition[end_month]": _this.defect_month[1],
          "queryCondition[misStart]": _this.defectMisRange[0],
          "queryCondition[misEnd]": _this.defectMisRange[1],
          "queryCondition[lamp_type]": _this.defect_lamp_type,
          "queryCondition[base]": _this.defect_base,
          "queryCondition[customer_id]": _this.defectMainPlantId,
          "queryCondition[simple_call]": _this.defect_simple_call,
          functionParam: JSON.stringify(params)
        },
        callBack(res) {
          if (res.success && res.rows.length > 0) {
            _this.defectBarData = res.rows;
            _this.defectTotalCount = _this.defectBarData.reduce((sum, item) => sum + parseInt(item.num), 0);
            _this.renderDefectBarChart();

            // 清空饼图
            _this.currentDefect = '';
            _this.renderDefectPieChart([]);
          } else {
            _this.defectBarData = [];
            _this.defectTotalCount = 0;
            _this.renderDefectBarChart();
            _this.renderDefectPieChart([]);
          }
        }
      });
    },

    loadDefectPieData(defectName) {
      let _this = this;
      let params = {"SQL": this.cal_defect_pie_sql};
      
      // 如果defect_name是"无"，需要特殊处理SQL
      if (defectName === '无') {
        // 修改SQL，替换 d.FIRST_ANALYSE = #{defect_name} 为 (d.FIRST_ANALYSE IS NULL OR d.FIRST_ANALYSE = '')
        if (this.defectType === 'DESCRIBE') {
          params.SQL = this.cal_defect_pie_sql.replace("a.consumer_describe_extract = #{defect_name}", "(a.consumer_describe_extract IS NULL OR a.consumer_describe_extract = '')");
        } else {
          params.SQL = this.cal_defect_pie_sql.replace("d.FIRST_ANALYSE = #{defect_name}", "(d.FIRST_ANALYSE IS NULL OR d.FIRST_ANALYSE = '')");
        }
      }

      app.utils.ajaxRequest({
        hideMsg: true,
        hideMask: true,
        url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
        params: {
          "queryCondition[defect_name]": defectName !== '无' ? defectName : '',
          "queryCondition[start_month]": _this.defect_month[0],
          "queryCondition[end_month]": _this.defect_month[1],
          "queryCondition[misStart]": _this.defectMisRange[0],
          "queryCondition[misEnd]": _this.defectMisRange[1],
          "queryCondition[lamp_type]": _this.defect_lamp_type,
          "queryCondition[base]": _this.defect_base,
          "queryCondition[customer_id]": _this.defectMainPlantId,
          functionParam: JSON.stringify(params)
        },
        callBack(res) {
          if (res.success && res.rows.length > 0) {
            _this.defectPieData = res.rows;
            _this.renderDefectPieChart(_this.defectPieData);
          } else {
            _this.defectPieData = [];
            _this.renderDefectPieChart([]);
          }
        }
      });
    },

    renderDefectBarChart() {
      this.chartDefectBarTarget = this.chartDefectBarTarget || this.$echarts.init(this.$refs.defectBarTarget);
      // 确保图表布局正确
      setTimeout(() => {
        if (this.chartDefectBarTarget) {
          this.chartDefectBarTarget.resize();
        }
      }, 200);

      // 如果没有数据，显示提示信息
      if (!this.defectBarData || !this.defectBarData.length) {
        let emptyOption = {
          title: {
            text: '当前查询条件下无数据',
            left: 'center',
            top: 'middle',
            textStyle: {
              fontSize: 16,
              fontWeight: 'bold'
            }
          }
        };
        this.chartDefectBarTarget.setOption(emptyOption, true);
        return;
      }

      // 准备数据
      let nameList = [];
      let valueList = [];
      let percentList = [];
      let cumulativeList = [];
      let cumulative = 0;

      // 按数量降序排序
      this.defectBarData.sort((a, b) => b.num - a.num);

      this.defectBarData.forEach((item) => {
        nameList.push(item.name);
        valueList.push(item.num);

        // 计算百分比和累计百分比
        const percent = this.defectTotalCount > 0 ? (item.num / this.defectTotalCount * 100) : 0;
        percentList.push(percent.toFixed(2));

        cumulative += percent;
        cumulativeList.push(cumulative.toFixed(2));
      });

      let option = {
        color: ['#3A86FF', '#FFB703', '#8AC926'], // 蓝色柱子，黄色占比，绿色累计线
        title: {
          text: `【${this.defect_lamp_type_show}】${this.defect_base ? '【'+this.defect_base_show+'】' : ''}${this.defectMainPlantName ? '【'+this.defectMainPlantName+'】' : ''}【${this.defect_month[0] || ''}至${this.defect_month[1] || ''}】【${this.defect_mis}】缺陷分布总和`,
          left: '2%',
          textStyle: {
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            let tooltip = params[0].name + '<br/>';
            params.forEach((param, index) => {
              if (index === 0) {
                tooltip += `${param.seriesName}: ${param.value} (${percentList[param.dataIndex]}%)<br/>`;
              } else if (index === 1) {
                tooltip += `${param.seriesName}: ${percentList[param.dataIndex]}%<br/>`;
              } else {
                tooltip += `${param.seriesName}: ${param.value}%<br/>`;
              }
            });
            return tooltip;
          }
        },
        legend: {
          data: ['数量', '占比', '累计占比'],
          right: '5%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: nameList,
            axisLabel: {
              interval: 0,
              rotate: 30,
              textStyle: {
                fontSize: 10
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '数量',
            position: 'left',
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '百分比',
            position: 'right',
            axisLabel: {
              formatter: '{value}%'
            },
            max: 100
          }
        ],
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: nameList.length > 10 ? Math.round(1000 / nameList.length) : 100,
            xAxisIndex: [0, 1]
          },
          {
            type: 'inside',
            realtime: true,
            start: 0,
            end: nameList.length > 10 ? Math.round(1000 / nameList.length) : 100,
            xAxisIndex: [0, 1]
          }
        ],
        series: [
          {
            name: '数量',
            type: 'bar',
            barMaxWidth: 40,
            barMinWidth: 20,
            data: valueList,
            itemStyle: {
              normal: {
                barBorderRadius: [3, 3, 0, 0],
                label: {
                  show: true,
                  position: 'top',
                  formatter: (params) => params.value
                }
              }
            }
          },
          {
            name: '占比',
            type: 'bar',
            barMaxWidth: 40,
            barMinWidth: 20,
            yAxisIndex: 1,
            data: percentList,
            itemStyle: {
              normal: {
                barBorderRadius: [3, 3, 0, 0],
                label: {
                  show: true,
                  position: 'top',
                  formatter: (params) => params.value + '%'
                }
              }
            }
          },
          {
            name: '累计占比',
            type: 'line',
            yAxisIndex: 1,
            data: cumulativeList,
            symbol: 'circle',
            symbolSize: 8,
            smooth: true,
            lineStyle: {
              width: 3
            },
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  formatter: (params) => params.value + '%'
                }
              }
            }
          }
        ]
      };

      option && this.chartDefectBarTarget.setOption(option, true);

      // 添加点击事件
      let _this = this;
      this.chartDefectBarTarget.off('click');
      this.chartDefectBarTarget.on('click', function(params) {
        if (params.componentType === 'series' && (params.seriesName === '数量' || params.seriesName === '占比')) {
          _this.currentDefect = params.name;
          _this.loadDefectPieData(params.name);
        }
      });
      
      // 自动加载第一个柱子的饼图数据
      if (this.defectBarData.length > 0) {
        this.currentDefect = this.defectBarData[0].name;
        this.loadDefectPieData(this.defectBarData[0].name);
      }
    },

    renderDefectPieChart(data) {
      this.chartDefectPieTarget = this.chartDefectPieTarget || this.$echarts.init(this.$refs.defectPieTarget);

      // 确保图表布局正确
      setTimeout(() => {
        if (this.chartDefectPieTarget) {
          this.chartDefectPieTarget.resize();
        }
      }, 200);
      if (!data || data.length === 0) {
        let emptyOption = {
          title: {
            text: '请点击左侧柱状图查看产品简称分布',
            left: 'center',
            top: 'middle',
            textStyle: {
              fontSize: 16,
              fontWeight: 'bold'
            }
          }
        };
        this.chartDefectPieTarget.setOption(emptyOption, true);
        return;
      }

      // 准备饼图数据
      let pieData = data.map(item => {
        return {
          name: item.simple_call,
          value: parseInt(item.num)
        };
      });

      // 按数量降序排序
      pieData.sort((a, b) => b.value - a.value);

      let option = {
        title: {
          text: `【${this.defect_lamp_type_show}】${this.defect_base ? '【'+this.defect_base_show+'】' : ''}${this.defectMainPlantName ? '【'+this.defectMainPlantName+'】' : ''}【${this.defect_month[0] || ''}至${this.defect_month[1] || ''}】【${this.currentDefect}】缺陷的产品简称分布`,
          left: '2%',
          textStyle: {
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          //orient: 'vertical',
          left:'4%',
          right: '4%',
          top: 20,
          //bottom: 20,
          data: pieData.map(item => item.name)
        },
        series: [
          {
            name: '产品简称',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '50%'],
            top:'12%',
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}:\n {c} ({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: pieData
          }
        ]
      };

      option && this.chartDefectPieTarget.setOption(option, true);
    },

    // 退回产品排布相关方法
    loadReturnBarData() {
      let _this = this;
      this.returnNameList = [];
      this.returnSeriesList = [];
      // 重置当前选中数据，防止保留旧数据
      this.return_mis = '';
      this.referred_simple_call = '';
      this.defectList = [];

      // 问题数量统计
      let params = {"SQL": this.return_bar_sql};
      app.utils.ajaxRequest({
        hideMsg: true,
        hideMask: true,
        url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
        params: {
          "queryCondition[lamp_type]": _this.return_lamp_type,
          "queryCondition[base]": _this.return_base,
          "queryCondition[customer_id]": _this.returnMainPlantId,
          "queryCondition[simple_call]": _this.return_simple_call,
          "queryCondition[start_month]": _this.return_month[0],
          "queryCondition[end_month]": _this.return_month[1],
          functionParam: JSON.stringify(params)
        },
        callBack(res) {
          if (res.success && res.rows.length > 0) {
            let dataList = res.rows;
            if (dataList.length > 30) {
              _this.dataZoomStart = 100 - Math.ceil(3000/dataList.length);
            } else {
              _this.dataZoomStart = 0;
            }
            let data3 = [];
            let data6 = [];
            let data9 = [];
            let data12 = [];
            let data24 = [];
            let data36 = [];
            let nameList = [];

            dataList.forEach((item) => {
              nameList.push({value:item.simple_call,id:item.simple_call_id});
              data3.push(item.mis3);
              data6.push(item.mis6);
              data9.push(item.mis9);
              data12.push(item.mis12);
              data24.push(item.mis24);
              data36.push(item.mis36);
            })
            let rawData = [data3, data6, data9, data12,data24,data36];
            const seriesList = ['3MIS', '6MIS', '9MIS', '12MIS','24MIS','36MIS'].map((name, sid) => {
              return {
                name,
                type: 'bar',
                stack: 'total',
                barMaxWidth: 60,
                barMinWidth: 25,
                emphasis: {
                  focus: 'series'
                },
                itemStyle: {
                  normal: {
                    barBorderRadius: [3, 3, 3, 3],
                    label: {
                      show: true,
                      formatter: (params) => params.value == 0 ? '' : params.value
                    },
                  }
                },
                data: rawData[sid]
              };
            });
            _this.returnNameList = nameList;
            _this.returnSeriesList = seriesList;
          }
          _this.renderReturnBarChart();
          // 无论上方图表有没有数据，都要重置下方图表
          _this.loadEmptyLineChart();
        },
      });
    },

    renderReturnBarChart(){
      this.chartReturnBarTarget = this.chartReturnBarTarget || this.$echarts.init(this.$refs.returnBarTarget);

      // 确保图表布局正确
      setTimeout(() => {
        if (this.chartReturnBarTarget) {
          this.chartReturnBarTarget.resize();
        }
      }, 200);

      // 如果没有数据，显示提示信息
      if (!this.returnNameList.length || !this.returnSeriesList.length) {
        let emptyOption = {
          title: {
            text: '当前查询条件下无数据',
            left: 'center',
            top: 'middle',
            textStyle: {
              fontSize: 16,
              fontWeight: 'bold'
            }
          }
        };
        this.chartReturnBarTarget.setOption(emptyOption, true);
        return;
      }

      // 不再需要计算总数，使用calculateTotalCount方法

      let option = {
        color: ['#388E3C','#1976D2', '#FBC02D','#FB8C00','#EC407A', '#D32F2F'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            let tooltip = params[0].name + '<br/>';
            let itemTotal = 0;
            params.forEach(param => {
              tooltip += `${param.seriesName}: ${param.value}<br/>`;
              itemTotal += parseInt(param.value || 0);
            });
            tooltip += `<b>总计: ${itemTotal}</b>`;
            return tooltip;
          }
        },
                  legend: {right: '5%',top:20, data: ['3MIS', '6MIS', '9MIS', '12MIS', '24MIS', '36MIS']},
          title: {
            text: '【'+this.return_lamp_type_show+'】'+(this.return_base ? '【'+this.return_base_show+'】' : '')+(this.returnMainPlantName ? '【'+this.returnMainPlantName+'】' : '')+'【'+this.return_month[0]+'至'+this.return_month[1]+'】退回产品排布',
            left: '2%',
            textStyle: {
              fontSize: 14
            }
          },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          show: false,
          right: '3%',
          feature: {
            magicType: {
              type: ["line", "bar"]
            },
          }
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              show: false
            },
            axisLabel: {
              interval: 0,
              rotate: 30,
              textStyle: {
                fontSize: 10
              }
            },
            data: this.returnNameList
          },
        ],
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: this.returnNameList.length > 10 ? Math.round(1000 / this.returnNameList.length) : 100,
            xAxisIndex: [0, 1]
          },
          {
            type: 'inside',
            realtime: true,
            start: 0,
            end: this.returnNameList.length > 10 ? Math.round(1000 / this.returnNameList.length) : 100,
            xAxisIndex: [0, 1]
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '退回数',
            axisLabel: {
              formatter: '{value} 个'
            }
          },
        ],
        series: this.returnSeriesList
      };

      let _this = this;
      option && this.chartReturnBarTarget.setOption(option, true);
      this.chartReturnBarTarget.off('click');
      this.chartReturnBarTarget.on('click', function (params) {
        _this.return_mis = params.seriesName;
        _this.referred_simple_call = params.name;
        _this.loadLineRateData();
      });
      
      // 自动加载第一个柱子的第一个柱形(3MIS)的缺陷统计
      if (this.returnNameList.length > 0) {
        this.return_mis = '3MIS';
        this.referred_simple_call = this.returnNameList[0].value;
        this.loadLineRateData();
      }
    },

    // 添加一个新方法显示空的线图，只有提示文字
    loadEmptyLineChart() {
      this.chartReturnLineTarget = this.chartReturnLineTarget || this.$echarts.init(this.$refs.returnLineTarget);
      let emptyOption = {
        title: {
          text: '请点击左侧柱状图查看缺陷分布总和',
          left: 'center',
          top: 'middle',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        }
      };
      this.chartReturnLineTarget.setOption(emptyOption, true);
    },

    loadLineRateData() {
      let _this = this;
      let months = this.getMonthStartAndEnd(this.return_month[0]); // 使用起始月份的第一天
      let lastMonthDate = this.getMonthStartAndEnd(this.return_month[1]); // 使用结束月份的最后一天
      if(!this.return_mis){
        this.loadLineRateChart();
        return;
      }

      // 将两个请求封装为Promise
      const moleculePromise = new Promise((resolve) => {
        _this.loadLineRateMolecule(resolve);
      });

      const denominatorPromise = new Promise((resolve) => {
        let params = {"SQL": this.denominator_sql};
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            "queryCondition[referred_simple_call]": _this.referred_simple_call,
            "queryCondition[startDate]": months[0],
            "queryCondition[endDate]": lastMonthDate[1],
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            let total_num = 0;
            if (res.success) {
              total_num = res.rows[0].num;
              resolve(total_num);
            }
          }
        });
      });

      // 等待两个Promise都完成
      Promise.all([moleculePromise, denominatorPromise]).then((results) => {
        const total_num = results[1];
        _this.loadLineRateChart(total_num);
      });
    },

    // 修改loadLineRateMolecule以支持回调
    loadLineRateMolecule(callback) {
      let _this = this;
      let params = {"SQL": this.return_defect_sql};
      
      // 修改SQL，处理'无'的情况
      if (this.returnDefectType === 'DESCRIBE') {
        params.SQL = this.return_defect_sql.replace("ifnull(a.consumer_describe_extract, '无') as name", 
          "CASE WHEN a.consumer_describe_extract IS NULL OR a.consumer_describe_extract = '' THEN '无' ELSE a.consumer_describe_extract END as name");
      } else {
        params.SQL = this.return_defect_sql.replace("ifnull(d.FIRST_ANALYSE,'无') as name", 
          "CASE WHEN d.FIRST_ANALYSE IS NULL OR d.FIRST_ANALYSE = '' THEN '无' ELSE d.FIRST_ANALYSE END as name");
      }
      
      app.utils.ajaxRequest({
        hideMsg: true,
        hideMask: true,
        url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
        params: {
          "queryCondition[referred_simple_call]": _this.referred_simple_call,
          "queryCondition[start_month]": _this.return_month[0],
          "queryCondition[end_month]": _this.return_month[1],
          "queryCondition[base]": _this.return_base,
          "queryCondition[customer_id]": _this.returnMainPlantId,
          "queryCondition[misStart]": _this.returnMisRange[0],
          "queryCondition[misEnd]": _this.returnMisRange[1],
          functionParam: JSON.stringify(params)
        },
        callBack(res) {
          _this.defectList = [];
          if (res.success) {
            _this.defectList = res.rows;
            if (callback) callback();
          }
        }
      });
    },

    loadLineRateChart(total_num){
      let _this = this;
      this.chartReturnLineTarget = this.chartReturnLineTarget || this.$echarts.init(this.$refs.returnLineTarget);

      // 确保图表布局正确
      setTimeout(() => {
        if (this.chartReturnLineTarget) {
          this.chartReturnLineTarget.resize();
        }
      }, 200);

      // 如果没有数据，显示提示信息
      if (!this.defectList || !this.defectList.length) {
        let emptyOption = {
          title: {
            text: '当前选择条件下无数据',
            left: 'center',
            top: 'middle',
            textStyle: {
              fontSize: 16,
              fontWeight: 'bold'
            }
          }
        };
        this.chartReturnLineTarget.setOption(emptyOption, true);
        return;
      }

      // 创建带有原始索引的数据对象
      let dataWithIndex = this.defectList.map((item, index) => {
        let value = 0;
        if(total_num > 0){
          value = (item.num*1000/total_num).toFixed(4);
        }
        return {
          name: item.name,
          value: value,
          originalNum: item.num
        };
      });

      // 按照值从高到低排序
      dataWithIndex.sort((a, b) => b.value - a.value);

      // 提取排序后的名称和数据列表
      let nameList = dataWithIndex.map(item => item.name);
      let dataList = dataWithIndex.map(item => item.value);

      let option = {
        title: {
          text: '【'+this.referred_simple_call+'】'+(this.return_base ? '【'+this.return_base_show+'】' : '')+(this.returnMainPlantName ? '【'+this.returnMainPlantName+'】' : '')+'【'+this.return_month[0]+'至'+this.return_month[1]+'】【'+this.return_mis+'】缺陷统计',
          top:'1%',
          left: '1%',
          textStyle: {
            fontSize: 13,
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const index = params[0].dataIndex;
            const originalNum = dataWithIndex[index].originalNum;
            return `${params[0].name}<br/>${params[0].seriesName}: ${params[0].value}‰<br/>数量: ${originalNum}`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: nameList,
          axisLabel: {
            interval: 0,
            rotate: 30,
            textStyle: {
              fontSize: 10
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '千分比',
          axisLabel: {
            formatter: '{value}‰'
          }
        },
        series: [
          {
            name: '千分比',
            data: dataList,
            type: 'line',
            smooth: true,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  formatter: (params) => params.value + '‰'
                },
              }
            },
          }
        ]
      };

      option && this.chartReturnLineTarget.setOption(option);
    },

    // 图表控制方法
    toggleFullscreen() {
      this.is_fullscreen = !this.is_fullscreen;
      setTimeout(() => {
        this.resizeAllCharts();
      }, 300);
    },

    resizeAllCharts() {
      if (this.chartDefectBarTarget) {
        this.chartDefectBarTarget.resize();
      }
      if (this.chartDefectPieTarget) {
        this.chartDefectPieTarget.resize();
      }
      if (this.chartReturnBarTarget) {
        this.chartReturnBarTarget.resize();
      }
      if (this.chartReturnLineTarget) {
        this.chartReturnLineTarget.resize();
      }
    },
    loadMainPlant(){
       let _this = this;
      _this.mainPlantItems = [];
      app.utils.ajaxRequest({
        hideMsg: true,
        hideMask: true,
        url: app.path().dispose + "?functionCode=QMS_MAIN_ENGINE_PLANT_SELECT",
        params: {is_queryPage: false},
        callBack(res) {
          if (res.success && res.rows.length > 0) {
            let dataList = res.rows;
            let plantList = [];
            dataList.forEach((item) => {
              let map = {};
              map.text = item.main_engine_plant_name;
              map.value = item.id;
              plantList.push(map);
            })
            _this.mainPlantItems = plantList;
          }
        },
      })
    },
  },
  mounted() {
    this.loadTypes();
    this.loadBases();

    this.loadMainPlant();
    // 分别加载两部分数据
    this.loadDefectData();
    this.loadReturnData();

    // 延迟执行一次图表重绘，以确保布局稳定
    this.$nextTick(() => {
      setTimeout(() => {
        this.resizeAllCharts();
      }, 500);
    });

    // 添加窗口大小变化时的图表重绘逻辑
    window.onresize = () => {
      this.resizeAllCharts();
    };
  }
}
</script>
